package com.superbit.service.mq.impl;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.springframework.stereotype.Service;

import com.superbit.core.exception.ServerErrorException;
import com.superbit.service.mq.define.ActiveMQSessionKeeper;
import com.superbit.service.mq.define.ActiveMqService;
import com.superbit.service.mq.define.MQMessSender;
import com.superbit.service.mq.define.MQMessageHandler;


@Service
public class ActiveMqServiceImpl implements ActiveMqService{
	
	@Resource(name="MQSessionKeeper")
	private ActiveMQSessionKeeper sessionKeeper;
	
	//发送者
	private Map<Integer,MQMessSender> messageSenderMap = new HashMap<Integer,MQMessSender>();
	//接收器
	private Map<Integer,MQMessageHandler> messageHandlerMap = new HashMap<Integer,MQMessageHandler>();
	
	@Override
	public void addMessageSender(int matchType,MQMessSender sender){
		messageSenderMap.put(matchType, sender);
	}
	
	@Override
	public void addMessageHandler(int matchType,MQMessageHandler handler){
		messageHandlerMap.put(matchType, handler);
	}
	
	private MQMessSender getMessSender(int matchType){
		return messageSenderMap.get(matchType);
	}
	
	private MQMessageHandler getMessHandler(int matchType){
		return messageHandlerMap.get(matchType);
	}
	
	@Override
	public void sendOrderMessage(int matchType,int messagetype,Object order) {
		MQMessSender messSender = this.getMessSender(matchType);
		if(messSender==null){			
			throw new ServerErrorException( "MessSendDer Not Set", null);
		}
		this.sendMessage(messSender,messagetype, order);
	}
	
	@Override
	public void dealWithMessage(int matchType, int tradeType, Message message) {
		MQMessageHandler messHandler = this.getMessHandler(matchType);
		if(messHandler==null){			
			throw new ServerErrorException( "MessHandler Not Set", null);
		}
		messHandler.handle(tradeType,message);
	}

	
	private void sendMessage(MQMessSender messSender,int messagetype,Object order){
		Session session = sessionKeeper.getActiveSession();
		if(session==null){
			throw new ServerErrorException("MQConnection Lose",null);
		}
		try{			
			Message message = messSender.createMessageByObj(messagetype, order, session);
			if(message!=null){				
				sessionKeeper.sendOrderMessage(messSender.getDestinationName(),message);
			}else{
				throw new ServerErrorException("MessageBuild Error", null);
			}
		}catch(JMSException e){
			throw new ServerErrorException("MessageBuild Error", null);
		}
	}	
}
